package com.zhkj.txg.module.home.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.HomeBannerAdapter
import com.zhkj.txg.module.home.adapter.HomeCateAdapter
import com.zhkj.txg.module.home.adapter.MarketGoodsAdapter
import com.zhkj.txg.module.home.entity.BannerEntity
import com.zhkj.txg.module.home.vm.MarketViewModel
import com.zhkj.txg.utils.GridItemDecoration
import com.zhkj.txg.utils.typeJump
import com.youth.banner.Banner
import kotlinx.android.synthetic.main.activity_market.*
import kotlin.math.abs

class MarketActivity : ViewModelActivity<MarketViewModel>() {
    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, MarketActivity::class.java)
            activity.startActivity(intent)
        }
    }

    override fun setViewModel(): MarketViewModel = createViewModel()
    override fun statusTitleBar(): View? = topViewMarket
    override val layoutResId: Int = R.layout.activity_market

    private lateinit var bannerTop: Banner<BannerEntity, HomeBannerAdapter>
    private var maxScrollHeight = 0
    private val categoryAdapter = HomeCateAdapter().apply {
        setOnItemClickListener { _, _, position ->
            val category = data[position]
            SecondCategoryActivity.open(this@MarketActivity, category.id)
        }
    }
    private val goodsAdapter = MarketGoodsAdapter().apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener { viewModel.marketProduct(AccountManager.getToken()) }
    }

    override fun initUI() {
        // 获取变色的最大滚动距离
        topViewMarket.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                maxScrollHeight =
                    (ScreenUtil.getScreenWidth(this@MarketActivity) * 0.75 - topViewMarket.measuredHeight).toInt()
                topViewMarket.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        with(rvMarket) {
            layoutManager = GridLayoutManager(this@MarketActivity, 3).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
            }
            addItemDecoration(
                GridItemDecoration(
                    ScreenUtil.dip(this@MarketActivity, 20),
                    ScreenUtil.dip(this@MarketActivity, 10)
                )
            )
            adapter = goodsAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                val llm = layoutManager as GridLayoutManager
                val pos = IntArray(2)
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    // 设置title的透明度
                    if (llm.findFirstVisibleItemPosition() == 0 && llm.getChildAt(0) != null) {
                        llm.getChildAt(0)!!.getLocationInWindow(pos)
                        if (abs(pos[1]) <= maxScrollHeight) {
                            val alpha = (abs(pos[1]).toFloat() / maxScrollHeight * 255).toInt()
                            topViewMarket.setBackgroundColor(Color.argb(alpha, 255, 255, 255))
                            titleMarket.setLeftIcon(R.drawable.ic_back)
                            tvMarketSearch.setBackgroundResource(R.drawable.bg_round_white_30dp_transparent)
                        } else {
                            topViewMarket.setBackgroundColor(Color.argb(255, 255, 255, 255))
                            titleMarket.setLeftIcon(R.drawable.ic_arrow_left_black)
                            tvMarketSearch.setBackgroundResource(R.drawable.bg_round_gray_100)
                        }
                    }
                }
            })
        }
        with(goodsAdapter) {
            setEmptyView(R.layout.layout_empty_data)
            headerWithEmptyEnable = true
            setHeaderView(createHeaderView())
        }
        // 打开搜索页面
        tvMarketSearch.setOnClickListener {
            SearchActivity.marketOpen(this, 0)
        }
        // 打开购物车
        ivBasket.setOnClickListener {
            startActivity(Intent(this, CartActivity::class.java))
        }
    }

    override fun initViewModel() {
        viewModel.marketProductLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 数据填充
                    if (it.loadMore) goodsAdapter.addData(it.data)
                    else goodsAdapter.setNewData(it.data)
                    // 判断加载状态
                    if (it.hasMore) goodsAdapter.loadMoreModule?.loadMoreComplete()
                    else goodsAdapter.loadMoreModule?.loadMoreEnd()
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    goodsAdapter.loadMoreModule?.loadMoreFail()
                }
            }
        })
        viewModel.marketLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) it.response?.data?.let { data ->
                // 设置轮播图
                bannerTop.setDatas(data.banner).start()
                // 设置分类
                categoryAdapter.setNewData(data.category)
            }
        })
    }

    override fun initData() {
        viewModel.marketData(AccountManager.getToken())
    }

    /**
     * 生成顶部视图
     */
    private fun createHeaderView(): View {
        return layoutInflater.inflate(R.layout.item_top_header, null).apply {
            bannerTop = findViewById(R.id.bannerTop)
            // 设置轮播图
            bannerTop.addBannerLifecycleObserver(this@MarketActivity).setAdapter(HomeBannerAdapter(context))
                .setOnBannerListener { data, _ ->
                    (data as? BannerEntity)?.let {
                        typeJump(this@MarketActivity, it.jumpType ?: 0, it.params, it.title)
                    }
                }
            with(findViewById<RecyclerView>(R.id.rvTop)) {
                layoutManager = GridLayoutManager(this@MarketActivity, 5)
                adapter = categoryAdapter
            }
        }
    }
}